package com.atguigu.gmall.ums.service.impl;

import com.atguigu.core.exception.MemberException;
import com.atguigu.core.utils.SmsUtils;
import com.atguigu.gmall.ums.service.RedisService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.Query;
import com.atguigu.core.bean.QueryCondition;

import com.atguigu.gmall.ums.dao.MemberDao;
import com.atguigu.gmall.ums.entity.MemberEntity;
import com.atguigu.gmall.ums.service.MemberService;



@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Value("${alisms.accessKeyId}")
    private String accessKeyId;

    @Value("${alisms.accessSecret}")
    private String accessSecret;

    @Autowired
    RedisService redisService;

    private static long CODE_EXPIRE_SECONDS = 600;    //设置验证码过期时间为600秒

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public MemberEntity queryUser(String username, String password) {
        // 查询
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", username));
        // 校验用户名
        if (memberEntity == null) {
            return null;
            //throw  new MemberException("用户名不存在");
        }

        //对输入的密码进行家眼加密
        password=DigestUtils.md5Hex(memberEntity.getSalt()+password);

        if(StringUtils.equals(password,memberEntity.getPassword())){
            //如果相同，则返回
            return memberEntity;
        }
        return null;
    }

    /**
     * 手机号验证码
     * @param mobile
     */
    @Override
    public void sendSms(String mobile) {
        // 生成随机六位数
        String code = RandomStringUtils.randomNumeric(6);
        redisService.remove(mobile);     //清除未失效的key对应的value值
        redisService.set(mobile, code);   //缓存新的key-value值
        redisService.expire(mobile, CODE_EXPIRE_SECONDS);  //设置过期时间   CODE_EXPIRE_SECONDS

        //发送短信
        SmsUtils.sendCode(accessKeyId,accessSecret,mobile,code);
    }

    /**
     * 注册用户
     * @param memberEntity
     * @param code
     */
    @Override
    public void register(MemberEntity memberEntity, String code) {
        //校验手机验证码
        String code2 = redisService.get(memberEntity.getMobile());   //调用方法根据key获取缓存中对应的验证码
        if (StringUtils.isEmpty(code2)) {    //判断验证码是失效，未取到则为失效
            throw new MemberException("验证码失效");
        } else if (!"".equals(code2) && !code.equals(code2)) {   //判断接收的验证码是否和缓存中的一致
            throw new MemberException("验证码错误");
        }

        //2、生成盐
        String salt = UUID.randomUUID().toString().substring(0, 6);
        memberEntity.setSalt(salt);
        //3、密码加盐加密
        String md5Hex = DigestUtils.md5Hex(salt + memberEntity.getPassword());
        memberEntity.setPassword(md5Hex);

        memberEntity.setGrowth(0);
        memberEntity.setIntegration(0);
        memberEntity.setLevelId(0l);
        memberEntity.setCreateTime(new Date());
        memberEntity.setStatus(1);
        //4、新增用户
        boolean saveflag = this.save(memberEntity);
        if(!saveflag){
            throw new MemberException("注册失败");
        }
        //5、删除redis中的验证吗
        redisService.remove(memberEntity.getMobile());
    }



    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageVo(page);
    }

    /**
     * 校验用户名是否存在
     * @param data
     * @param type
     * @return
     */
    @Override
    public Boolean checkData(String data, Integer type) {
        QueryWrapper<MemberEntity> wrapper=new QueryWrapper<>();
        switch (type){
            case 1:
                wrapper.eq("username", data);
                break;
            case 2:
                wrapper.eq("mobile", data);
                break;
            case 3:
                wrapper.eq("email", data);
                break;
            default:
                return false;

        }
        return this.count(wrapper)==0;//等于0代表可用
    }

}